var util = require('../../utils/util.js');
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    loadingHidden: false, // loading
    swiperCurrent: 0,
    selectCurrent: 0,
    CurrentPage: 1,
    goodsResult: [],
    classify: [],
    scrollTop: "0",
    loadingMoreHidden: false,
    fromuid: 0, //通过分享带来的分享人ID
    caseArry: [],
    caseArry2: [],
    newslist: [],
    newslist2: [],
    newsone: [],
    newstwo: [],
    categories: [],
    newsArray: [],
    selList: '', //选中的购物车项键列表
    Config: [],
    videoSrc: '',
    supportCompany: "",
    supportPhone: "",
    swiper_h: 1,
    GroupBuyProduct: [],
    DisplayPosition: 0,
    titleImg: "",
    pathGoods: "",
    positionBtnO: {},
    positionBtnTw: {},
    positionBtnTh: {},
    positionBtnF: {},
    contact: false,
    searchbg: "",
    classifyNav: [],
    navDisplayType: 0,
    scrollLeft: 0,
    logo: "",
    storeName: '',
    vid: "",
    msgLength: 0,
    FromAccountNick: "",
    FromAccountImage: "",
    showTopPopup: false,
    FromAccount: "",
    typeList: [],
    isopenred: false,
    userStaff: {},
    mobile: "",
    isAiweapp: true,
    officialAccount: 0, //是否显示公众号组件
    query: ''
  },

  /**
   * 首页定制商品展示
   */
  GetGoodsList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetWidgetList?storeId=' + app.globalData.storeId + '&code=index_product',
      success: function (res) {
        if (res.data.Code == 0) {
          var Config = res.data.Data.Config
          for (var i = 0; i < Config.length; i++) {
            Config[i].ShowImg = app.globalData.image_logo_banner + Config[i].ShowImg
            Config[i].DisplayProductList = []
            var ProductInfos = Config[i].DisplayProductInfos
            for (var j = 0; j < ProductInfos.length; j++) {
              var h = {}
              h.Pid = ProductInfos[j].Pid
              h.Name = ProductInfos[j].Name
              h.ShowImg = app.globalData.image800_800host + ProductInfos[j].ShowImg
              h.ShopPrice = ProductInfos[j].ShopPrice
              h.SaleCount = ProductInfos[j].SaleCount
              h.MarketPrice = ProductInfos[j].MarketPrice
              h.StoreCid = ProductInfos[j].StoreCid
              h.SKUGid = ProductInfos[j].SKUGid
              h.StockNumber = ProductInfos[j].StockNumber
              if (ProductInfos[j].SKUGid == 0) {
                Config[i].DisplayProductList.push(h)
              } else {
                if (!that.checkProduct(Config[i].DisplayProductList, ProductInfos[j].SKUGid)) {
                  Config[i].DisplayProductList.push(h)
                }
              }
            }
          }
          that.setData({
            Config: Config
          })
        }
      }
    })
  },

  //sku产品去重
  checkProduct: function (productList, text) {
    var state = false; //默认不存在
    if (productList.length > 0 & text != 0) {
      for (var i = 0; i < productList.length; i++) {
        if (text == productList[i].SKUGid) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },

  /**
   * 获取拼团商品列表
   */
  getGroupBuyProduct: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyIndexProduct?storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          var pruduct = []
          var ProductList = res.data.Data.Items
          var rawData = res.data.Data.Page;
          var time = util.formatTime(new Date());
          for (var i = 0; i < ProductList.length; i++) {
            if (util.compareDate(ProductList[i].GroupBuy.EndTime, time)) {
              if (ProductList[i].Product && ProductList[i].GroupBuy.Status == 0) {
                var c = {}
                c.Pid = ProductList[i].Product.Pid
                c.Name = ProductList[i].Product.Name
                c.ShowImg = app.globalData.image800_800host + ProductList[i].Product.ShowImg
                c.SaleCount = ProductList[i].Product.SaleCount
                c.ShopPrice = ProductList[i].Product.ShopPrice
                c.MarketPrice = ProductList[i].Product.MarketPrice
                c.StoreCid = ProductList[i].Product.StoreCid
                pruduct.push(c)
              }
            }
          }
          if (res.data.Data.Setting.ShowImg) {
            var titleImg = 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/logo/source/' + res.data.Data.Setting.ShowImg
          } else {
            var titleImg = ""
          }
          that.setData({
            GroupBuyProduct: pruduct,
            DisplayPosition: res.data.Data.Setting.DisplayPosition,
            titleImg: titleImg,
            showIndex: res.data.Data.Setting.ShowIndex
          })
        }
      }
    })
  },

  toGroupbuyTap: function (e) {
    wx.navigateTo({
      url: "/pages/pintuan-details/index?id=" + e.currentTarget.dataset.id
    })
  },

  selectCoupon: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var c = that.data.validCouponList[index];
    wx.setStorageSync(that.data.selList, c);
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 领取优惠券
   */
  getCoupon: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var couponType = that.data.typeList[index];
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCoupon',
      data: {
        couponTypeId: couponType.CouponTypeId,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showModal({
            title: '提示',
            content: '领取成功',
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },

  tapBanner: function (e) {
    var id = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name
    var linktype = e.currentTarget.dataset.linktype
    var url = e.currentTarget.dataset.url
    var mobile = e.currentTarget.dataset.mobile
    if (id != 0) {
      if (linktype == "product") { //产品详情
        wx.navigateTo({
          url: "/pages/goods-details/index?id=" + id,
        })
      } else if (linktype == "store_class") { //产品分类
        wx.navigateTo({
          url: "/pages/classesTwo/index?id=" + id + "&&name=" + name,
        })
      } else if (linktype == "news") { //新闻详情
        wx.navigateTo({
          url: '/pages/news-details/index?newsid=' + id,
        })
      } else if (linktype == "news_type") { //新闻列表
        wx.navigateTo({
          url: '/pages/news-list/index?newstypeid=' + id,
        })
      } else if (linktype == "page" && id == 1) { //优惠劵
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 2) { //关于
        wx.setStorageSync("tap", 0);
        wx.reLaunch({
          url: url
        })
      } else if (linktype == "page" && id == 3) { //在线客服
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 4) { //申请分销
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 5) { //预约留言
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 6) { //联系方式
        wx.setStorageSync("tap", 1);
        wx.reLaunch({
          url: url
        })
      } else if (linktype == "page" && id == 7) { //一键导航
        wx.setStorageSync("tap", 2);
        wx.reLaunch({
          url: url
        })
      } else if (linktype == "page" && id == 8) { //拼团
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 9) { //限时秒杀
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 10) { //留言管理
        wx.navigateTo({
          url: url
        })
      } else if (linktype == "page" && id == 11) { //所有商品
        wx.navigateTo({
          url: url
        })
      } else {
        wx.navigateTo({
          url: url
        })
      }
    } else if (id == 0 && linktype == "h5page") { //h5网页
      wx.navigateTo({
        url: '/pages/h5page/index?url=' + url,
      })
    } else if (id == 0 && linktype == "phonecall") { //一键拨号
      wx.makePhoneCall({
        phoneNumber: !isNaN(mobile) ? mobile : name
      })
    } else if (id == 0 && linktype == "weappfunc") { //小程序功能（客服/扫一扫）
      if (mobile == "scancode" || name == "scancode") {
        wx.scanCode({
          success: (res) => {
            wx.redirectTo({
              url: res.path,
            })
          }
        })
      } else if (app.globalData.userStaff) {
        // var name = encodeURIComponent(app.globalData.userStaff.Name);
        // var seltoid = app.globalData.userStaff.Uid
        // wx.navigateTo({
        //   url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
        // })
        util.tapChat(app.globalData.userStaff);
      }
    } else {
      wx.navigateTo({
        url: url
      })
    }
  },

  //拨打服务商电话
  callCompany: function () {
    var that = this;
    if (that.data.supportPhone == '') {
      return
    } else {
      wx.makePhoneCall({
        phoneNumber: that.data.supportPhone
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    console.log("首页options", e);
    let params = decodeURIComponent(e.scene);
    console.log('小程序码携带的参数', params);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let type = 1;//路由
      let param = '';//参数
      let plist = '';
      if (params.indexOf('p-') != -1) {
        type = params.match(/t-(\S*)\*p/)[1];//路由
        param = params.match(/p-(\S*)/)[1];//参数
        plist = param.toString().split('_');
      } else {
        type = params.match(/t=(\S*)&p/)[1];//路由
        param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      if (type == 10) {//分销二维码
        if (plist[0]) {
          wx.setStorageSync("disid", plist[0]);
        }
        if (plist[1]) {
          wx.setStorageSync("agentid", plist[1]);
        }
      }
    } else {
      if (e.agentId) {
        wx.setStorageSync("agentid", e.agentId);
      }
      if (e.disId) {
        wx.setStorageSync("disid", e.disId);
      }
      var st = 2;
      if (e.st) {
        st = e.st;
      }
      if (e.sl) {
        that.setData({
          selList: e.sl
        });
      }
      that.setData({
        st: st
      });
      if (e.fromuid) { //通过别人分享的链接打开GetImgsListFour
        wx.setStorageSync("fromuid", e.fromuid);
      }
    }
    // return;
    that.initOnloadData();
    util.isAiWeApp(app, function (data) {
      that.setData({
        isAiweapp: data
      })
    });
    that.setData({
      storeid: app.globalData.storeId
    })

    wx.setNavigationBarTitle({
      title: wx.getStorageSync('mallName')
    })

    app.callbackWeapp = () => {
      if (that.data.isAiweapp) {
        that.tapChat();
      }
    }
  },

  //加载数据
  initOnloadData: function () {
    app.resthttp({
      url: app.globalData.host + '/api/Store/GetInfo',
      data: {
        id: app.globalData.storeId
      }
    }).then(res => {
      this.data.logo = "https://static.711688.net.cn/upload/store/" + app.globalData.storeId + "/logo/source/" + res.data.Data.Logo;
      this.data.storeName = res.data.Data.Name;
      this.data.supportPhone = res.data.Data.SupportPhone;
      this.setData({
        videoSrc: res.data.Data.VideoSrc,
        supportCompany: res.data.Data.SupportCompany,
        vid: res.data.Data.VID,
        officialAccount: res.data.Data.OfficialAccount
      })
    }).then(() => {
      this.ToNavIcon()
    }).then(() => {
      this.GetGoodsList()
    })
      .then(() => {
        this.newsShow()
      })
      .then(() => {
        this.getGroupBuyProduct()
      })
      .then(() => {
        this.getWidgetFloatOne()
      })
      .then(() => {
        this.getWidgetFloatTwo()
      })
      .then(() => {
        this.getWidgetFloatThree()
      })
      .then(() => {
        this.getWidgetFloatFour()
      })
      .catch(res => {
      })
  },

  //首页悬浮组件
  getWidgetFloatOne: function () { //左中部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=11",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnO: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  getWidgetFloatTwo: function () { //左底部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=12",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnTw: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  getWidgetFloatThree: function () { //右中部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=13",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnTh: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  getWidgetFloatFour: function () { //右底部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=14",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnF: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  /**
   * 按钮导航
   */
  ToNavIcon: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/GetWidgetList?storeid=' + app.globalData.storeId + '&code=index_nav_icon',
      success: function (res) {
        if (res.data.Code == 0) {
          var newbs = [];
          var rawData = res.data.Data.Config;
          var Widget = res.data.Data.Widget;
          if (Widget.IsActive) { //是否展示
            if (!Widget.DisplayType) { //分类导航展示方式0-默认，1-横滑
              for (let k = 0; k < rawData.length; k++) {
                rawData[k].ShowImg = app.globalData.image_logo_banner + rawData[k].ShowImg;
              }
              that.setData({
                classifyNav: rawData
              })
            } else {
              for (let h = 0; h < rawData.length; h++) {
                rawData[h].ShowImg = app.globalData.image_logo_banner + rawData[h].ShowImg;
              }
              for (var i = 0, len = rawData.length; i < len; i += 8) {
                newbs.push(rawData.slice(i, i + 8));
              }
              that.setData({
                classify: newbs,
                scrollLeft: 48
              });
            }
          }
        }
      }
    })
  },

  //获取手机号
  getPhoneNumber: function (e) {
    util.getMobile(e);
    if (app.globalData.userStaff) {
      // var name = encodeURIComponent(app.globalData.userStaff.Name);
      // var seltoid = app.globalData.userStaff.Uid
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
      // })
      util.tapChat(app.globalData.userStaff);
    }
  },

  onShow: function () {
    var that = this;
    var closetimes = wx.getStorageSync("closetimes");
    var mobile = wx.getStorageSync("mobile");
    if (mobile) {
      that.setData({
        mobile: mobile
      })
    }
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      if (app.globalData.userStaff) {
        that.onMyEvent(app.globalData.userInfo.Uid);
        that.getMsgUnRead();
        var tabBarObj = wx.getStorageSync("tabBarObj");
        if (tabBarObj && tabBarObj.list[0]) {
          util.aiCardActionRecord(23, JSON.stringify(tabBarObj.list[0].text));
        }
      }

      if (closetimes != 2) { //手动关闭超过两次取消弹出
        that.GetCouponTypeList();
      }

      wx.setNavigationBarTitle({
        title: wx.getStorageSync('mallName')
      })
      that.GetSharePagePath()
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  onMyEvent: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let fromuid = res.data.Data.Id;
            wx.connectSocket({
              url: app.globalData.socketUrl,
              success: function (res) {
                console.log('创建一个 WebSocket 连接', res);
              },
              fail: function (err) {
                console.log('创建一个 WebSocket 连接失败', err);
              }
            })
            // 监听连接成功
            wx.onSocketOpen(function () {
              console.log('socket连接成功者', fromuid);
              let datas = { "type": "connect", "from_uid": fromuid };
              wx.sendSocketMessage({
                data: JSON.stringify(datas),
                success: function (res) {
                  console.log('发送成功', res);
                }, fail: function (err) {
                  console.log('发送失败', err);
                }
              })
            })
            // 监听 WebSocket 接受到服务器的消息
            wx.onSocketMessage(message => {
              //把JSONStr转为JSON
              message = message.data.replace(" ", "");
              if (typeof message != 'object') {
                message = message.replace(/\ufeff/g, ""); //重点
                var jj = JSON.parse(message);
                message = jj;
                if (message.type == 'send' && message.content) {
                  let msgLength = that.data.msgLength;
                  that.setData({
                    msgLength: msgLength + 1
                  })
                }
              }
              console.log("【websocket监听到消息】内容如下：", message);
            })
            wx.onSocketError(function (err) {
              console.log('监听 WebSocket 错误事件', err);
            });
            wx.onSocketClose(function (res) {
              console.log('WebSocket 已关闭啦啦啦！', res)
            });
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  tapSearch: function (e) {
    wx.navigateTo({
      url: "/pages/classes/index"
    })
  },

  onPullDownRefresh: function () {
    var that = this;
    wx.showToast({
      title: '正在刷新',
      duration: 1500,
      icon: 'loading',
      success: function () {
        that.setData({
          CurrentPage: 1
        })
        that.GetGoodsList();
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    })
  },

  onShareAppMessage: function () { //分享
    return {
      title: wx.getStorageSync('mallName'),
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    let imageUrl = that.data.logo;
    let query = that.data.query;
    return {
      title: that.data.storeName,
      query: query,
      imageUrl: imageUrl
    }
  },

  //获取分销商信息
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        disId: disId,
        agentId: agentId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var path = '';
          var fromuid = app.globalData.userInfo.Uid;
          if (res.data.Data.IsAgent == 0) {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          } else {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          }
          let query = 'fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId + '&isFriendState=1';
          that.data.query = query;
          that.data.pathGoods = path;
        }
      }
    })
  },

  //跳转案例列表
  exampleList: function (e) {
    var newstypeid = e.currentTarget.dataset.newstypeid
    wx.navigateTo({
      url: '/pages/news-list/index?newstypeid=' + newstypeid,
    })
  },

  //跳转文章详情
  toArtcle: function (e) {
    var newsid = e.currentTarget.dataset.newsid
    wx.navigateTo({
      url: '/pages/news-details/index?newsid=' + newsid,
    })
  },

  newsShow: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/news/StoreNewsTypeList?storeid=' + app.globalData.storeId + '&hasnews=1',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            newsArray: res.data.Data
          })
        }
      }
    })
  },

  //跳聊天页
  tapChat: function () {
    if (app.globalData.userStaff) {
      // var name = encodeURIComponent(app.globalData.userStaff.Name);
      // var seltoid = app.globalData.userStaff.Uid
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
      // })
      util.tapChat(app.globalData.userStaff);
    }
  },

  //获取未读消息
  getMsgUnRead: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/WebIM/GetUnRead?uid=' + app.globalData.userInfo.Uid + "&stuffUId=" + app.globalData.userStaff.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            msgLength: res.data.Data
          })
        }
      },
    })
  },

  // 顶部消息提醒进入聊天
  // tapChatFrom: function() {
  //   if (app.globalData.userStaff) {
  //     var name = encodeURIComponent(this.data.FromAccountNick);
  //     var seltoid = this.data.FromAccount;
  //     wx.navigateTo({
  //       url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
  //     })
  //   }
  // },

  //用户可领取的优惠券
  GetCouponTypeList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetSendingCouponTypeList',
      data: {
        storeid: app.globalData.storeId,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var couPonList = res.data.Data
          for (var i = 0; i < couPonList.length; i++) {
            couPonList[i].UseStartTime = couPonList[i].SendStartTime.slice(0, 10)
            couPonList[i].UseEndTime = couPonList[i].SendEndTime.slice(0, 10)
          }
          that.setData({
            typeList: res.data.Data,
            userStaff: app.globalData.userStaff
          })
        }
      }
    })
  },

  /**
   * 领取优惠券
   */
  getOpenRed: function (e) {
    var that = this;
    that.setData({
      isopenred: true
    })
    var typeList = that.data.typeList;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCoupon',
      data: {
        couponTypeId: typeList[0].CouponTypeId,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            isopenred: true
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //使用优惠券
  couponUse: function () {
    this.setData({
      typeList: [],
      isopenred: false
    })
  },

  //关闭弹框
  closeRed: function () {
    var that = this;
    var closetimes = wx.getStorageSync("closetimes");
    wx.showModal({
      title: '提示',
      content: '是否放弃领取优惠',
      success: function (res) {
        if (res.confirm) {
          if (!closetimes) {
            closetimes = 0;
          }
          closetimes++;
          wx.setStorageSync("closetimes", closetimes);
          that.setData({
            typeList: [],
            isopenred: false
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //离开当前页面
  onUnload: function () {
    util.toCloseSocket();
  },
  onHide: function () {
    util.toCloseSocket();
  }
})